<?php
require_once '../config.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 获取用户信息
$userId = getCurrentUserId();
$pdo = getDB();

// 检查用户是否是被邀请的
$stmt = $pdo->prepare("SELECT is_invited FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
$isInvited = $user['is_invited'] ?? 0;

// 检查用户是否已经中过奖
$stmt = $pdo->prepare("
    SELECT COUNT(*) FROM winning_records 
    WHERE user_id = ? 
    AND prize_id != ? 
   
");
// AND DATE(created_at) = CURDATE()
$stmt->execute([$userId, DEFAULT_PRIZE_ID]);
$hasWon = $stmt->fetchColumn() > 0;

// 速率限制检查
if (!checkRateLimit()) {
    echo json_encode(['success' => false, 'message' => '请求过于频繁，请稍后再试']);
    exit;
}

// 检查每日抽奖次数
if (!checkDailyLimit()) {
    echo json_encode([
        'success' => false, 
        'message' => '您的抽奖次数已用完，祝您新春快乐',
        'code' => 'LIMIT_EXCEEDED'
    ]);
    exit;
}

try {
    $pdo = getDB();
    $pdo->beginTransaction();

    // 获取所有可用奖品
    $stmt = $pdo->query("SELECT id, name, total_quantity, remaining_quantity, probability 
        FROM prizes 
        WHERE remaining_quantity > 0 
        ORDER BY id ASC");
    $prizes = $stmt->fetchAll();

    // 如果用户不是被邀请的或已经中过奖，强制抽中"谢谢参与"
    if (!$isInvited || $hasWon) {
        foreach ($prizes as $prize) {
            if ($prize['id'] == DEFAULT_PRIZE_ID) {
                $prize = $prize;
                break;
            }
        }
    } else {
        // 正常抽奖逻辑
        $prize = calculatePrize($prizes);
    }
    
    if ($prize) {
        // 更新奖品库存
        $stmt = $pdo->prepare("UPDATE prizes SET remaining_quantity = remaining_quantity - 1 WHERE id = ? AND remaining_quantity > 0");
        $result = $stmt->execute([$prize['id']]);

        if ($result) {
            // 记录中奖信息
            // 获取用户的邀请码
            $stmt = $pdo->prepare("SELECT invite_code FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            
            // 插入中奖记录，包含邀请码
            $stmt = $pdo->prepare("INSERT INTO winning_records (user_id, prize_id, invite_code) VALUES (?, ?, ?)");
            $stmt->execute([$userId, $prize['id'], $user['invite_code']]);

            $pdo->commit();
            
            // 直接使用当前奖品列表计算索引
            // $prizeIndex = array_search($prize['id'], array_column($prizes, 'id'));
            $prizeIndex = $prize['id'] - 1;
            
            echo json_encode([
                'success' => true,
                'prize' => $prize,
                'prizeIndex' => $prizeIndex,
                'debug' => [
                    'prize_id' => $prize['id'],
                    'prize_name' => $prize['name'],
                    'index' => $prizeIndex,
                    'user_id' => $userId,
                    'invite_code' => $user['invite_code'] ?? null
                ]
            ]);
        } else {
            throw new Exception('更新奖品库存失败');
        }
    } else {
        $pdo->commit();
        echo json_encode([
            'success' => true,
            'prize' => null,
            'message' => '很遗憾，未中奖'
        ]);
    }
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => '系统错误，请稍后重试']);
    error_log($e->getMessage());
}

function calculatePrize($prizes) {
    $totalProbability = 0;
    foreach ($prizes as $prize) {
        if (!isset($prize['probability']) || !is_numeric($prize['probability'])) {
            error_log("Invalid probability for prize ID {$prize['id']}");
            continue;
        }
        $totalProbability += $prize['probability'];
    }

    if ($totalProbability <= 0) {
        error_log("Total probability is 0 or negative");
        return null;
    }

    $random = mt_rand() / mt_getrandmax();
    $currentProbability = 0;

    foreach ($prizes as $prize) {
        if (!isset($prize['probability']) || !is_numeric($prize['probability'])) {
            continue;
        }
        $currentProbability += $prize['probability'] / $totalProbability;
        if ($random <= $currentProbability) {
            return $prize;
        }
    }

    return null;
} 